package controller;


import util.LogUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;


public abstract class BaseServlet extends HttpServlet {
    private final Logger logger = LogUtils.getLogger();

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //请求乱码
        req.setCharacterEncoding("UTF-8");
        //响应乱码
        resp.setContentType("text/html;charset=UTF-8");
        String action = req.getParameter("action");
        String path = null;
        //获取action业务
        try {
            Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
            Method[] methods = this.getClass().getDeclaredMethods();
            Map<String, String> params = new HashMap();
            //Map<String, String[]> parameterMap = req.getParameterMap();
            Enumeration<String> parameterNames = req.getParameterNames();
            String name = null;
            String value = null;
            while (parameterNames.hasMoreElements()) {
                name = parameterNames.nextElement();
                if (name != "action") {
                    value = req.getParameter(name);
                    params.put(name, value);
                }

            }
            //System.out.println(params);
            //System.out.println(params.toString());
            //Map<String, String[]> parameterMap = req.getParameterMap();
//            BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream()));
//            int body = IOUtils.read(reader);
//            String jsString =JSON.toJSONString(parameterMap);
            ZonedDateTime zdf = ZonedDateTime.now();
            String sDate = zdf.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            logger.info(sDate);
            logger.info("--执行了" + method.getName() + "方法");
            logger.info("--请求的参数为：" + params.toString() + "\n");
            //调用目标业务 方法
            try {
                path = (String) method.invoke(this, req, resp);
                //System.out.println(path);
            } catch (InvocationTargetException e) {
                e.printStackTrace();
                logger.info("\n异常信息：在执行时发生" + e.getMessage() + "异常\n");
                resp.sendRedirect("/error.jsp");
            } catch (IllegalAccessException e) {
//                e.printStackTrace();
                logger.info("\n异常信息：在执行时发生" + e.getMessage() + "异常\n");
                resp.sendRedirect("/error.jsp");
            }
        } catch (NoSuchMethodException | IOException e) {
//            e.printStackTrace();
            logger.info("\n异常信息：在执行时发生" + e.getMessage() + "异常\n");
            resp.sendRedirect("/error.jsp");
        }
        //System.out.println(path.substring(0,1));
        //System.out.println(path.substring(2,path.length()));
        if (path == null || path.equals("")) {
            return;
        } else {
            //转发
            if (path.substring(0, 1).equals("s")) {
                resp.sendRedirect(path.substring(2, path.length()));
            }
            //重定向
            if (path.substring(0, 1).equals("g")) {
                try {
                    req.getRequestDispatcher(path.substring(2, path.length())).forward(req, resp);
                } catch (ServletException e) {
                    logger.info("\n异常信息：在执行时发生" + e.getMessage() + "异常\n");
//                    e.printStackTrace();
                }

            } else throw new RuntimeException("服务器错误");
        }

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

}
